#include"Settings.h" 

#include"StatusBar.h"

#include<QDir>
#include<QFile>

const QString Settings::SETTINGS_FILE = "settings";
const QString Settings::SETTINGS_DIR = QDir::homePath() + QDir::separator() + ".sqdp" + QDir::separator();
Settings *Settings::_settings = 0;

Settings::Settings(const QString &filename):QObject(0){
	general = new General;
	general->_changed = false;
	lastfm = new LastFM;
	lastfm->_changed = false;
	defaultSettings();
	
	QFile file(filename);
	if(!file.open(QIODevice::ReadOnly)){
		write();
	}else{
		QByteArray ba;
		while(!file.atEnd()){
			ba = file.readLine();
			if(ba.isEmpty() || ba.startsWith('#'))
				continue;
			QStringList strl = QString(ba).split('=', QString::SkipEmptyParts);
			if(strl.size() != 2)
				continue;
			strl[1].remove('\n');
			if(strl[0].startsWith("General."))
				readGeneralSetting(strl[0].remove("General."), strl[1]);
			else if(strl[0].startsWith("LastFM."))
				readLFMSetting(strl[0].remove("LastFM."), strl[1]);
		}
		file.close();
	}
}

void Settings::readGeneralSetting(QString setting, QString value){
	printf("Setting: %s\nValue: %s\n", setting.toUtf8().data(), value.toUtf8().data());
	if(setting == "musicDir")
		general->musicDir = value;
	else if(setting == "usePlaylist")
		general->usePlaylist = (value != "0");
}

void Settings::readLFMSetting(QString setting, QString value){
	printf("Setting: %s\nValue: %s\n", setting.toUtf8().data(), value.toUtf8().data());
	if(setting == "offerCorrections")
		lastfm->offerCorrections = (value != "0");
}

void Settings::write(){
	QDir dir(SETTINGS_DIR);
	if(!dir.exists())
		dir.mkpath(SETTINGS_DIR);
	QFile file(SETTINGS_DIR+SETTINGS_FILE);
	if(!file.open(QIODevice::WriteOnly)){
		sStatusBar->log("Failed saving settings.\n");
		return;
	}
	
	//General
	file.write( QString("General.musicDir=" + general->musicDir + "\n").toUtf8() );
	file.write( (QString("General.usePlaylist=") + (general->usePlaylist ? "1\n" : "0\n") ).toUtf8() );
	
	//LastFM
	file.write( (QString("LastFM.offerCorrections=") + (lastfm->offerCorrections ? "1\n" : "0\n") ).toUtf8() );
	
	file.close();
	bool anythingChanged = false;
	if(general->_changed){
		general->_changed = false;
		anythingChanged = true;
		emit generalChanged();
	}
	if(lastfm->_changed){
		lastfm->_changed = false;
		anythingChanged = true;
		emit lastfmChanged();
	}
	if(anythingChanged)
		emit changed();
}

void Settings::defaultSettings(){
	//General
	general->musicDir = QDir::homePath() + QDir::separator() + "Music" + QDir::separator();
	general->usePlaylist = true;
	
	//LastFM
	lastfm->offerCorrections = true;
	lastfm->isScrobbling = false;
}

Settings *Settings::instance(){
	if(!_settings)
		_settings = new Settings(SETTINGS_DIR+SETTINGS_FILE);
	return _settings;
}

bool Settings::isChanged()const{
	return	lastfm->_changed
	||	general->_changed;
}
